package com.hanqi.yupicturebackend;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class ImageSearchExample {
    public static void main(String[] args) {
        // 替换为你的App Key和图片URL
        String appKey = "YOUR_APP_KEY";
        String appSecret = "YOUR_APP_SECRET";
        String imgUrl = "http://example.com/image.jpg"; // 替换为实际图片URL

        try {
            String result = searchItemsByImage(appKey, appSecret, imgUrl);
            System.out.println("搜索结果：");
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String searchItemsByImage(String appKey, String appSecret, String imgUrl) throws Exception {
        StringBuilder result = new StringBuilder();
        String apiUrl = "https://eco.taobao.com/router/rest";

        // 构造请求参数
        String params = "method=item_search_img&app_key=" + appKey + "&v=2.0&format=json&sign_method=md5&q=女装&img_url=" + URLEncoder.encode(imgUrl, "UTF-8");

        URL url = new URL(apiUrl + "?" + params);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        int responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            return "Failed : HTTP error code : " + responseCode;
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result.append(inputLine);
        }
        in.close();

        return result.toString();
    }
}